//
//  MXPublishView.m
//  CatchBear
//
//  Created by 王启颖 on 2019/2/6.
//  Copyright © 2019 王启颖. All rights reserved.
//

#import "MXPublishView.h"
#import "XMTextView.h"
#import <Photos/Photos.h>

#import "UICollectionViewLeftAlignedLayout.h"
#import "LPTagModel.h"
#import "LPTagCell.h"
#import "LPTagTextFieldCell.h"
#import "BTKMyProfileTagViewController.h"
#import "UIImage+UIImageZLK.h"

@interface MXPublishView ()<UICollectionViewDataSource, UICollectionViewDelegateLeftAlignedLayout>{
    NSInteger countImgNum;
    UIButton *sel_Btn;
}
@property (strong, nonatomic) XMTextView *tv;
@property (copy, nonatomic) NSString *tv_str;
@property (strong, nonatomic) UIImageView *img_View;
@property (strong, nonatomic) UIButton *num_Btn;
@property (strong, nonatomic) UIView *lineView;
@property (strong, nonatomic) UIButton *addTag_Btn;
@property (strong, nonatomic) NSMutableArray *paramsArr;
@property (strong, nonatomic) NSMutableArray *imgURLArr;
@property (strong, nonatomic) NSArray *tagArr;
@property (strong, nonatomic) UICollectionView *selectedCollectionView;
@property (strong, nonatomic) UIButton *selPic_Btn;
@property (strong, nonatomic) UIButton *selComic_Btn;
@end
@implementation MXPublishView

- (instancetype)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        [self initCustomerControls];
    }
    return self;
}

- (void)initCustomerControls {
    self.tv = [[XMTextView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth-2*16-100, 150)];
    _tv.isSetBorder = NO;
    _tv.maxNumColor = MX_WHITE_COLOR;
    _tv.textFont = [UIFont systemFontOfSize:12];
    _tv.placeholder = @"说点什么";
    WEAKSELF
    _tv.textViewListening = ^(NSString *textViewStr) {
        weakSelf.tv_str = textViewStr;
        NSLog(@"tv监听输入的内容：%@",textViewStr);
    };
    [self addSubview:_tv];
    
    self.img_View = [[UIImageView alloc]initWithFrame:CGRectMake(self.tv.mj_x+self.tv.width, 15, 100, 100)];
    [self addSubview:self.img_View];
    
    self.num_Btn = [UIButton buttonWithType:UIButtonTypeCustom];
    self.num_Btn.frame = CGRectMake(self.img_View.width-20, 10, 20, 15);
    self.num_Btn.backgroundColor = [UIColor colorWithRed:0 green:0 blue:0 alpha:0.6];
    self.num_Btn.titleLabel.font = [UIFont systemFontOfSize:9];
    [self.num_Btn setTitleColor:MX_WHITE_COLOR forState:UIControlStateNormal];
    [self.img_View addSubview:self.num_Btn];
    
    self.lineView = [[UIView alloc]initWithFrame:CGRectMake(0, _tv.height,kScreenWidth, 0.5)];
    self.lineView.backgroundColor = MX_LINE_COLOR;
    [self addSubview:self.lineView];
    
    
}



#pragma mark - 网络请求 -

//发布
- (void)publishClick{
    [SVProgressHUD show];
    NSMutableArray *upload_imgNameArray = [[NSMutableArray alloc]init];
    NSMutableArray *upload_imgSizeArray = [[NSMutableArray alloc]init];
    countImgNum = [self.imgURLArr count];
    for (NSString *filePath in self.imgURLArr) {
        [MXPublicRequstClass uploadImg:filePath success:^(id result) {
            [upload_imgNameArray addObject:[NSString stringWithFormat:@"%@%@",Img_URL,result[@"key"]]];
            UIImage *image = [UIImage imageWithContentsOfFile:filePath];
            [upload_imgSizeArray addObject:[NSString stringWithFormat:@"%ld*%ld",(long)image.size.width,(long)image.size.height]];
            
            countImgNum = countImgNum - 1;
            if (countImgNum == 0) {
                NSDictionary *dicParams = [NSDictionary dictionaryWithObjectsAndKeys:self.tv_str,@"messages_info",
                                           [MXUserMessageTool message].user_id,@"user_id",
                                           upload_imgNameArray,@"picture_arr",
                                           upload_imgSizeArray,@"picture_size",
                                           [NSString stringWithFormat:@"%d",(int)sel_Btn.tag - 100],@"messages_type", nil];
                
                NSLog(@"%@",dicParams);
                
                [[MXHttpManagerClass HttpRequstManager] PostURL:sendMessage params:dicParams isHearderparam:YES success:^(NSInteger code, id result) {
                    [SVProgressHUD dismiss];
                    
                    if (code == 0) {
                        NSLog(@"%@",result);
                        [[NSNotificationCenter defaultCenter] postNotificationName:@"YZSuccessLoginNotification" object:nil];
                        [self.navigationController popViewControllerAnimated:YES];
                    }else{
                        [SVProgressHUD showImage:NULL_IMAGE status:@"参数错误"];
                    }
                } fail:^(NSError *error) {
                    
                }];
            }
                
        }];
        
    }
    
}


#pragma mark - 图片数组赋值 -
- (void)setPublishImage:(UIImage *)publishImage{
    _publishImage = publishImage;
    self.img_View.image = publishImage;
    
    [self saveImage:publishImage];
    
}


- (void)saveImage:(UIImage *)image {
    NSArray *paths =NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask,YES);
    
    NSData *data = [self resetSizeOfImageData:image maxSize:kScreenWidth];
    UIImage *resultImage = [UIImage imageWithData:data];
    
    NSString *filePath = [[paths objectAtIndex:0]stringByAppendingPathComponent:
                          [NSString stringWithFormat:@"demo.png"]];  // 保存文件的名称
    
    BOOL result =[UIImagePNGRepresentation(resultImage)writeToFile:filePath   atomically:YES]; // 保存成功会返回YES
    if (result == YES) {
        NSLog(@"保存成功");
        [self.imgURLArr addObject:filePath];
    }
    
}

//压缩照片
- (NSData *)resetSizeOfImageData:(UIImage *)source_image maxSize:(NSInteger)maxSize {
    //先判断当前质量是否满足要求，不满足再进行压缩
    __block NSData *finallImageData = UIImageJPEGRepresentation(source_image,1.0);
    
    NSLog(@"---------------不压缩：%li",finallImageData.length/1024);
    NSUInteger sizeOrigin   = finallImageData.length;
    NSUInteger sizeOriginKB = sizeOrigin / 1024;
    
    if (sizeOriginKB <= maxSize) {
        return finallImageData;
    }
    
    //先调整分辨率
    CGSize defaultSize = CGSizeMake(1024, 1024);
    UIImage *newImage = [self newSizeImage:defaultSize image:source_image];
    
    finallImageData = UIImageJPEGRepresentation(newImage,1.0);
    
    //保存压缩系数
    NSMutableArray *compressionQualityArr = [NSMutableArray array];
    CGFloat avg   = 1.0/250;
    CGFloat value = avg;
    for (int i = 250; i >= 1; i--) {
        value = i*avg;
        [compressionQualityArr addObject:@(value)];
    }
    /*
     调整大小
     说明：压缩系数数组compressionQualityArr是从大到小存储。
     */
    //思路：使用二分法搜索
    finallImageData = [self halfFuntion:compressionQualityArr image:newImage sourceData:finallImageData maxSize:maxSize];
    //如果还是未能压缩到指定大小，则进行降分辨率
    while (finallImageData.length == 0) {
        //每次降100分辨率
        if (defaultSize.width-100 <= 0 || defaultSize.height-100 <= 0) {
            break;
        }
        defaultSize = CGSizeMake(defaultSize.width-100, defaultSize.height-100);
        UIImage *image = [self newSizeImage:defaultSize
                                      image:[UIImage imageWithData:UIImageJPEGRepresentation(newImage,[[compressionQualityArr lastObject] floatValue])]];
        finallImageData = [self halfFuntion:compressionQualityArr image:image sourceData:UIImageJPEGRepresentation(image,1.0) maxSize:maxSize];
    }
    NSLog(@"---------------压缩后：%li",finallImageData.length/1024);
    return finallImageData;
}

//调整图片分辨率/尺寸（等比例缩放）
- (UIImage *)newSizeImage:(CGSize)size image:(UIImage *)source_image {
    CGSize newSize = CGSizeMake(source_image.size.width, source_image.size.height);
    
    CGFloat tempHeight = newSize.height / size.height;
    CGFloat tempWidth = newSize.width / size.width;
    
    if (tempWidth > 1.0 && tempWidth > tempHeight) {
        newSize = CGSizeMake(source_image.size.width / tempWidth, source_image.size.height / tempWidth);
    }
    else if (tempHeight > 1.0 && tempWidth < tempHeight){
        newSize = CGSizeMake(source_image.size.width / tempHeight, source_image.size.height / tempHeight);
    }
    
    UIGraphicsBeginImageContext(newSize);
    [source_image drawInRect:CGRectMake(0,0,newSize.width,newSize.height)];
    UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return newImage;
}

//二分法
- (NSData *)halfFuntion:(NSArray *)arr image:(UIImage *)image sourceData:(NSData *)finallImageData maxSize:(NSInteger)maxSize {
    NSData *tempData = [NSData data];
    NSUInteger start = 0;
    NSUInteger end = arr.count - 1;
    NSUInteger index = 0;
    
    NSUInteger difference = NSIntegerMax;
    while(start <= end) {
        index = start + (end - start)/2;
        
        finallImageData = UIImageJPEGRepresentation(image,[arr[index] floatValue]);
        
        NSUInteger sizeOrigin = finallImageData.length;
        NSUInteger sizeOriginKB = sizeOrigin / 1024;
        //        NSLog(@"当前降到的质量：%ld", (unsigned long)sizeOriginKB);
        //        NSLog(@"\nstart：%zd\nend：%zd\nindex：%zd\n压缩系数：%lf", start, end, (unsigned long)index, [arr[index] floatValue]);
        
        if (sizeOriginKB > maxSize) {
            start = index + 1;
        } else if (sizeOriginKB < maxSize) {
            if (maxSize-sizeOriginKB < difference) {
                difference = maxSize-sizeOriginKB;
                tempData = finallImageData;
            }
            if (index<=0) {
                break;
            }
            end = index - 1;
        } else {
            break;
        }
    }
    return tempData;
}

//这个是选择照片用的（现在已经不用了）
- (void)setLastSelectAssets:(NSMutableArray<PHAsset *> *)lastSelectAssets{
    _lastSelectAssets = lastSelectAssets;

    for (int i = 0; i < lastSelectAssets.count; i++) {
        PHAsset *asset = lastSelectAssets[i];
        PHImageManager *manager = [PHImageManager defaultManager];
        [manager requestImageDataForAsset:asset options:nil resultHandler:^(NSData * _Nullable imageData, NSString * _Nullable dataUTI, UIImageOrientation orientation, NSDictionary * _Nullable info) {
            if (i == 0) {
                self.img_View.image = [UIImage imageWithData:imageData];
            }
            NSURL *url = [info valueForKey:@"PHImageFileURLKey"];
            NSString *urlStr = [[url absoluteString] stringByReplacingOccurrencesOfString:@"file:///" withString:@""];
            [self.imgURLArr addObject:urlStr];
        }];
    }
    
    
    if (lastSelectAssets.count > 1) {
        [self.num_Btn setTitle:[NSString stringWithFormat:@"%lu",(unsigned long)lastSelectAssets.count] forState:UIControlStateNormal];
    }else{
        [self.num_Btn setHidden:YES];
    }
}

#pragma mark - 懒加载 -
-(NSMutableArray *)paramsArr{
    if (!_paramsArr) {
        _paramsArr = [[NSMutableArray alloc]init];
    }
    return _paramsArr;
}
-(NSMutableArray *)imgURLArr{
    if (!_imgURLArr) {
        _imgURLArr = [[NSMutableArray alloc]init];
    }
    return _imgURLArr;
}


@end
